﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Submit_Click(object sender, EventArgs e)
    {
        string name = Username.Text.Trim();
        string password = Password.Text.Trim();

        CmsDataContext db = new CmsDataContext();
        var q = from aM in db.Manager
                where aM.ID == name
                select aM;

        if (q.Count() == 0)
        {
            MessageBox.Message = "用户名输入错误，请重新输入。";
        }
        else if (Toolkit.EncryptPassword(password) != q.First().Password)
        {
            MessageBox.Message = "密码输入错误，请重新输入。";
        }
        else
        {
            Manager m = q.First();

            Session["ManagerID"] = m.ID;
            Session["TeacherID"] = m.TeacherID;
            Session["ManagerName"] = m.Name;

            if (m.TeacherID == null)
            {
                //获取用户权限
                int power = 0;
                power = (from aP in db.Power
                         where aP.ManagerID == m.ID
                         select aP.Authority).ToList().Aggregate((a, b) => a | b);

                //.ToList().Aggregate((a, b) => a + b);
                Session["ManagerPower"] = power;
            }
            else if (m.Teacher.Verfied == null)
            {
                MessageBox.Message = "教师信息暂未审核，请稍后重试。";
                MessageBox.Location = "./Login.aspx";

                return;
            }
            else
            {
                Session["ManagerPower"] = Powers.Teacher;
            }

            Session["District"] = m.District;
            Session["Belong"] = m.Belong;

            if (m.TeacherID != null)
            {
                Session["PowerDescription"] = "教师用户";
            }

            if (Toolkit.HasPower(Powers.SystemManager))
            {
                try
                {
                    #region 删除临时文件夹下，5天之前创建的所有临时文件
                    string path = Server.MapPath(Toolkit.PathOfTemporary);
                    if (Directory.Exists(path))
                    {
                        var delfs = from aF in (new DirectoryInfo(path)).GetFiles()
                                    where aF.CreationTime.AddDays(5).Ticks <= DateTime.Now.Ticks
                                    select aF;

                        foreach (FileInfo f in delfs)
                        {
                            f.Delete();
                        }
                    }
                    #endregion
                }
                catch
                {
                }
            }

            Response.Redirect("~/Manage/Default.aspx");
        }
    }
}